# -*- coding: utf-8 -*-
# @Time    : 2017/5/10

from sympy import EmptySet
from mathsolver.functions.hanshu.dingyiyu import QiuDingYiYu
from mathsolver.functions.base import BaseSymbolValue, BaseFunction, new_latex
from mathsolver.functions.daoshu.jizhi import HanShuJiZhi
from mathsolver.functions.hanshu.helper import check_func, check_inter, yizhizhiyu_qiufanwei


class JiZhiDianCunZaiQiuCan(BaseFunction):
    """区间上存在极值点求参数范围"""
    jizhi = "极值"

    def solver(self, *args):
        func = check_func(args[0])

        # 如果题目不给定区间
        if len(args) == 2:
            interval = check_inter(args[1])
        else:
            interval = QiuDingYiYu().solver(func)

        jizhi_solver = HanShuJiZhi().solver(func)
        self.steps.extend(jizhi_solver.steps)

        if self.jizhi == "极大值":
            jizhi_result = jizhi_solver.jidazhidian
        elif self.jizhi == "极小值":
            jizhi_result = jizhi_solver.jixiaozhidian
        else:
            jizhi_result = jizhi_solver.jizhidian

        # 不含参数
        result = EmptySet()
        if isinstance(jizhi_result, list):
            for jizhi_x, jizhi_y in jizhi_result:
                piece_result = yizhizhiyu_qiufanwei(jizhi_x, interval)
                self.steps.append(["", "由题意知，极值点 %s 在区间 %s 内，解得：%s ∈ %s" %
                                   (new_latex(jizhi_x), new_latex(interval), new_latex(jizhi_solver.canshu), new_latex(piece_result))])
                result = result.union(piece_result)

        # 含参数
        else:
            for canshu_range, jizhis in jizhi_result.items():
                for jizhi_x, jizhi_y in jizhis:
                    piece_result = yizhizhiyu_qiufanwei(jizhi_x, interval)
                    piece_result = piece_result.intersect(canshu_range)
                    self.steps.append(["", "由题意知，极值点 %s 在区间 %s 内，解得：%s ∈ %s" %
                                       (new_latex(jizhi_x), new_latex(interval), new_latex(jizhi_solver.canshu),
                                        new_latex(piece_result))])
                    result = result.union(piece_result)

        # 计算问题里面的参数
        if jizhi_solver.canshu:
            question_canshu = jizhi_solver.canshu
        else:
            question_canshu = interval.free_symbols.pop()

        output_result = BaseSymbolValue({question_canshu: result})
        self.steps.append(['', "综上所述，%s" % output_result.printing()])
        self.output.append(output_result)
        self.label.add("区间上存在极值点求参数范围")
        return self


class JiDaZhiDianCunZaiQiuCan(JiZhiDianCunZaiQiuCan):
    """区间上存在极值点求参数范围"""
    jizhi = "极大值"


class JiXiaoZhiDianCunZaiQiuCan(JiZhiDianCunZaiQiuCan):
    """区间上存在极值点求参数范围"""
    jizhi = "极小值"


if __name__ == '__main__':
    pass
